package com.luluteam.pushlib.service.mqtt;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luluteam.pushlib.constant.AppHolder;
import com.luluteam.pushlib.model.DeviceInfo;
import com.luluteam.pushlib.model.PushLogin;
import com.luluteam.pushlib.model.PushMessage;
import com.luluteam.pushlib.model.PushReps;
import com.luluteam.pushlib.tools.NotificationHelper;
import com.luluteam.pushlib.tools.Repository;
import com.luluteam.pushlib.util.SharedPreferencesUtil;
import com.luluteam.pushlib.util.SystemUtils;
import com.luluteam.pushlib.util.okhttp.OkHttpManager;

import org.json.JSONException;

import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Guan
 * @date Created on 2018/1/6
 */
public class MqttService extends Service {

    private ExecutorService mqttExector = Executors.newSingleThreadExecutor();
    private static final String TAG = "MqttService";

    public MqttService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mqttExector.execute(new Runnable() {
            @Override
            public void run() {
                MqttClientManager.getInstance().start();
            }
        });
        sendDevice();
        sendLogin();
        Repository.getOfflineMsg(new OkHttpManager.ResultCallback() {
            @Override
            public void onSuccess(String result) {
                Log.i(TAG, "离线消息回调......" + result);
                Type type = new TypeToken<List<PushMessage>>() {
                }.getType();
                List<PushMessage> pushMessages = new Gson().fromJson(result, type);
                for (PushMessage pushMessage : pushMessages) {
                    sendPushMessageReceive(pushMessage);
                    NotificationHelper.sendNotification(AppHolder.appContext, pushMessage);
                }
            }
        });
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "stop mqtt Service");
        MqttClientManager.getInstance().stop();
        super.onDestroy();
    }

    /**
     * 发送设备信息
     */
    private void sendDevice() {

        boolean hasUploaded = SharedPreferencesUtil.getBoolean("hasUploaded");

        //如果是第一次上传，则上传设备信息
        if (!hasUploaded) {
            //得到设备号
            String deviceId = AppHolder.deviceId;
            //得到app版本
            String appVersion = SystemUtils.getInstance(this).getAppVersion();
            //得到手机设备生产商
            String manufacturer = SystemUtils.getInstance(this).getManufacturer();
            //得到操作系统版本
            String osVersion = SystemUtils.getInstance(this).getOsVersion();
            //得到sim卡运营商
            String simProvider = SystemUtils.getInstance(this).getSimProvider();
            //实例化设备信息对象
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setAppId(AppHolder.APP_ID);
            deviceInfo.setAppVersion(appVersion);
            deviceInfo.setDeviceId(deviceId);
            deviceInfo.setOsVersion(osVersion);
            deviceInfo.setSimProvider(simProvider);
            deviceInfo.setManufacturer(manufacturer);
            //上报设备信息
            Repository.postDeviceInfo(deviceInfo);

        }


    }

    /**
     * 向服务器发送登录信息
     *
     * @throws JSONException
     */
    private void sendLogin() {
        PushLogin pushLogin = new PushLogin();
        pushLogin.appId = AppHolder.APP_ID;
        pushLogin.deviceId = AppHolder.deviceId;
        Repository.postPushLogin(pushLogin);

    }


    /**
     * 接收到消息后，回应服务器，表示“成功接收”
     *
     * @param pushMessage
     */
    private void sendPushMessageReceive(PushMessage pushMessage) {
        PushReps pushReps = new PushReps();
        pushReps.appId = AppHolder.APP_ID;
        pushReps.deviceId = AppHolder.deviceId;
        pushReps.messageId = pushMessage.getMessageId();
        Repository.postPushReceive(pushReps);
    }

}
